<?php

namespace paper\bootstrap;

use paper\App;
use paper\Event;
use paper\exception\ErrorException;

class Loader
{
    private Event $event;

    public function __construct(App $app)
    {
    }

    public function onBoot()
    {

//        if (file_exists(ROOT_PATH . '/vendor/autoload.php')) {
//            require ROOT_PATH . '/vendor/autoload.php';
//        }
        /**
         * 因为compose会把autoload注册再队列开头，因此出于性能考虑我们把框架的注册放在后面
         * 但是同样添加在队列头部，这样我们的就会优先被调用
         */
        spl_autoload_register(function ($class) {
            $this->autoload($class);
        }, true, true);
        set_exception_handler([$this, 'appException']);
        set_error_handler([$this, 'appError']);
    }

    /**
     * @param $className
     */
    public function autoload($className)
    {
        $classpath = ROOT_PATH . DIRECTORY_SEPARATOR . str_replace("\\", DIRECTORY_SEPARATOR, $className);
        if (is_file($classpath)) {
            include($classpath);
        }
    }

    public function appError($errno, $errstr, $errfile, $errline)
    {
        $exception = new ErrorException($errno, $errstr, $errfile, $errline);
        $this->event->trigger(Event::EVENT_ERROR, [$exception]);
    }

    /**
     * @param \Throwable $exception
     * @return void
     */
    public function appException(\Throwable $exception)
    {
        $this->event->trigger(Event::EVENT_EXCEPTION, [$exception]);
    }


}